package com.imagination.applet.controller.web.configuration;

import com.imagination.applet.infrastructure.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        final String authorization = request.getHeader("Authorization");

        if (authorization != null && authorization.startsWith("Bearer ")) {
            String jwt = authorization.substring(7);
            Claims claims = JwtUtils.parse(jwt).getBody();
            Long userId = Long.parseLong(claims.get(JwtToken.USER_ID).toString());
            String openId = claims.get(JwtToken.OPEN_ID).toString();
            String openIdType = claims.get(JwtToken.OPEN_ID_TYPE).toString();
            String accessKey = claims.get(JwtToken.ACCESS_KEY).toString();
            SecurityContextHolder.getContext().setAuthentication(new JwtToken(userId, openId, openIdType, accessKey));
        }
        filterChain.doFilter(request, response);
    }
}
